﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;

namespace Mystery.SharePoint
{
	/// <summary>
	/// Extension methods for SPList
	/// </summary>
	public static class SPListExtensions
	{
		/// <summary>
		/// Gives the specified principal the speficifed role permissions to the list.
		/// Breaks inheritance if necessary. 
		/// </summary>
		/// <param name="list">The list to change permissions for</param>
		/// <param name="principal">The principal we are setting the permissions for</param>
		/// <param name="role">The role that represents the permissions the principal receives.</param>
		public static void SetPermission(this SPList list, SPPrincipal principal, SPRoleType role)
		{
			if (list == null) throw new ArgumentNullException("list");
			if (principal == null) throw new ArgumentNullException("principal");

			if (list.HasUniqueRoleAssignments == false)
			{
				list.BreakRoleInheritance(false);
			}
			
			SPRoleAssignment assignment = new SPRoleAssignment(principal);
			SPRoleDefinition definition = list.ParentWeb.RoleDefinitions.GetByType(role);

			assignment.RoleDefinitionBindings.Add(definition);
			list.RoleAssignments.Add(assignment);
		}

        
		/// <summary>
		/// Adds an existing field to the list if it already doesn't exist
		/// </summary>
		/// <param name="list"></param>
		/// <param name="id">ID of the field</param>
		/// <param name="options">Options for adding the field</param>
        public static void AddField(this SPList list, Guid id, SPAddFieldOptions options)
        {
            if (list == null) throw new ArgumentNullException("list");

            SPFieldCollection fields = list.Fields;
            SPFieldCollection availableFields = list.ParentWeb.AvailableFields;
            bool defaultView = ((options & SPAddFieldOptions.AddFieldToDefaultView) > 0);

            if ((fields.Contains(id) == false) && (availableFields.Contains(id) == true))
            {
                SPField field = availableFields[id];
                list.Fields.AddFieldAsXml(field.SchemaXmlWithResourceTokens, defaultView, options);
            }
        }
	}
}
